/**
 * 部门人员选择模块，提供人员单选及多选功能
 * 
 * @Date: 2015-6-16
 * @author: Jackson wang
 * @version: 1.0
 * @since: 1.0
 */
define(["jquery", "msgServ","ajaxServ","datagridServ","sysmanMain","btnServ","bizProto","init"], 
	function($,msgServ,ajaxServ,datagridServ,sysmanMain,btnServ,bizProto,init) {

	'use strict';

	var    $typedg,$typegrid,$detaildg,$detailgrid,$edit_window,_defaultConfig,
			$panel,_bizProto,_moduleConfig,_buttonConfig,
			$edit_window_height=700,$edit_window_width=900,
			docdetailEditUrl,
			$dg,$searchbox,
			doctypeQryUrl='/departmentHis/query/getTreeList.action',
			
			deptOwnerUrl = '/departmentHis/query/getTreeListByOwner.action',
			deptJobUrl = '/departmentHis/query/getTreeListByJobDept.action',
			
			docdetailQryUrl='/user/query/getListDomainByDeptid.action',
			docdetailSaveUrl='/docdetail/save.action',
			
		   	deptUserSelectUrl='/common/query/deptUserSelect.action',
			window_id='win-dept-user',
			window_width=800,
			window_height=600,
			openParam,
			select_type = {
				owner:'owner',
				job:'job',
				manageDept:'manageDept'
			}
    
	var	private_method = {
		init : function(_options) {
			
			_moduleConfig = sysmanMain.getCurrentModuConfig();
			
//			if (window.console) {
//				console.info(_moduleConfig.fullBizcode +' modules gets ready and been loaded.');
//			}
			_defaultConfig ={
				doc:null,
				rootId:null,				
				panelSelector:'div.well',
				subSystemCode:'sysman',
				moduleCode:'docdetail',
				btnSelector:'div.doc-detail-list-btn',
				doccode:null
			}
					
			_defaultConfig = $.extend({},_defaultConfig,_options)			
			_bizProto = new bizProto(_defaultConfig);			
			
			
			$edit_window = $('#win-dept-user');
				
			_buttonConfig={
				"选择":private_method.select,
				"重置":private_method.reset,
			    "取消":private_method.cancel,
			    "执行查询":private_method.doSearch
			}
			
			private_method.initElement(_bizProto.pageDoc)
		},
		
		initElement: function (doc) {
			//初始化操作按钮
			var listTd = $(doc).find(_defaultConfig.btnSelector)
			
						
			$typedg = $(doc).find("table.dg-type");
			
			//初始化列表高度和宽度
			var _height = openParam.height - 55
			
			if(window.console){
				console.log(' grid height : ' + _height)	
			}
			//_bizProto.gridHeight -=100
			var typeParam = {
				rownumbers:true,
				animate: true,									
				striped:true,
				border:true,
				//singleSelect:false,
				idField: 'id',
				treeField: 'name',					
				fitColumns: true,
				checkOnSelect:true,					
				selectOnCheck:true,
				height : _height,
				url : _bizProto.rootPath + doctypeQryUrl,
				onClickRow:private_method.getDocdetail
			}
			
			//设置初始化url
			if(openParam && openParam.selectByOwner){
				
				typeParam.url =_bizProto.rootPath + deptOwnerUrl
				if(openParam.subsystem){
					typeParam.url =typeParam.url+'?subsystem='+openParam.subsystem
				}
				
				
			}
			
			//设置初始化url
			if(openParam && openParam.selectType){
				var _url
				switch(openParam.selectType){
					case select_type.owner:
						_url = _bizProto.rootPath + deptOwnerUrl;
						break;
					case select_type.job:
						_url = _bizProto.rootPath + deptJobUrl;
						break;	
				}
				typeParam.url =_url
				if(openParam.subsystem){
					typeParam.url =typeParam.url+'?subsystem='+openParam.subsystem
				}
				
				
			}
			if(_defaultConfig.doccode){
				typeParam.queryParams={doccode:_defaultConfig.doccode}
			}
			$typegrid=$($typedg).treegrid(typeParam);
			
			//初始化完成后设置正常url
			$($typegrid).treegrid('options').url = _bizProto.rootPath + doctypeQryUrl,
			
			$detaildg = $(doc).find("table.dg-detail");
			
			
			
			var _detailParam = {
				rownumbers:true,
				animate: true,									
				striped:true,
				border:true,
				//singleSelect:false,
				idField: 'id',									
				fitColumns: true,
				checkOnSelect:true,
				pagination : true,
				selectOnCheck:true,
				height : _height,
				url : _bizProto.rootPath + docdetailQryUrl,
				toolbar:$(listTd)
			}
			if(openParam && openParam.singleSelect){
				_detailParam.singleSelect = true
			}
			$detailgrid=$($detaildg).datagrid(_detailParam);
			
			private_method.bindBtnEvent()
			
		},
		
		searchFunction:function(value,name){
			var _param = {}
	    	_param['searchName'] = name;_param['searchValue'] = value
	    	return _param;
		},
		 
		 getDocdetail:function (rowData){
		 	$detailgrid.datagrid('load',{deptid:rowData.id})			 
		},
		//绑定按钮事件
		bindBtnEvent:function(){
			// 绑定按钮事件
			var btn = $(_bizProto.pageDoc).find('div.doc-detail-list-btn a.function-btn')
			$(btn).unbind('click');
			$(btn).bind('click', private_method.function_btn_listenner)			
			
			
		},
		// 功能按钮监听函数
		function_btn_listenner : function(e) {

			btnServ.applyButton({buttonEvt:e,buttonConfig:_buttonConfig})

		},
		// 新增函数
		select : function() {
			var _tmpId =$($edit_window).attr('callback-id')
			//未设置dom参数，脚本打开的窗口
			if(!_tmpId ||$.trim(_tmpId)==''){
				private_method.scriptOpen()
			}
			
			var _tmpValue=$($edit_window).attr('callback-value')
			
			var records = $($detailgrid).datagrid('getSelections')
			
			if(!records ||　records.length<=0){
				msgServ.Msgslide('请选择人员');
				return
			}
			
			var selectedRecord =records[0]
			var selectedDept = $($typedg).datagrid('getSelected')
			//人员信息
			$('#'+_tmpId).val(selectedRecord.id)
			$('#'+_tmpValue).textbox('setText',selectedRecord.name)
			$('#'+_tmpValue).textbox('setValue',selectedRecord.name)
			
			//部门信息
			var _tmpDeptid =$($edit_window).attr('callback-deptid')
			var _tmpDeptValue=$($edit_window).attr('callback-deptValue')
			if(_tmpDeptid && $('#' +_tmpDeptid).length>0){
				$('#' +_tmpDeptid).val(selectedDept.id)
			}
			if(_tmpDeptValue && $('#' +_tmpDeptValue).length>0){
				$('#' +_tmpDeptValue).textbox('setValue',selectedDept.name)
			}
			$edit_window.window('close')
		},
		/**
		 * 脚本参数回调方法
		 */
		scriptOpen:function(){
			var _defaultConfig = {
				userids:null,
				usernames:null,
				deptid:null,
				deptname:null
			}
			
			//参数判断
			if(openParam){
				var records = $($detailgrid).datagrid('getSelections')
			
				if(!records ||　records.length<=0){
					msgServ.Msgslide('请选择人员');
					return
				}
				//var $typedg = $(doc).find("table.dg-type");
				var selectedRecord =records[0]
				//var selectedDept = $($typedg).datagrid('getSelected')
				_defaultConfig = $.extend({},_defaultConfig,openParam)
				var ids,names,deptName,selectedDeptId;
				//var ids,names
				for(var i=0;i<records.length;i++){
					ids = !ids?records[i].id:ids+','+records[i].id
					names = !names?records[i].name:names+','+records[i].name;
					deptName=!deptName?records[i].deptName:deptName+','+records[i].deptName;
					selectedDeptId = !selectedDeptId?records[i].deptid:selectedDeptId+','+records[i].deptid;
				}
				var selectedDept = $($typedg).datagrid('getSelected');
				
				if(openParam.callback){
					var _param = {
						userId:ids,
						userName:names,
						deptid:selectedDeptId,
						deptName:deptName,
						data:records
					}
					if(openParam.evt){
						_param.evt = openParam.evt	
					}
					openParam.callback(_param)
				}else{
					if(selectedDept){
						$('#'+_defaultConfig.userids).val(ids)
						$('#'+_defaultConfig.deptid).val(selectedDept.id)
						try{
							$('#'+_defaultConfig.usernames).textbox('setValue',names)
							$('#'+_defaultConfig.deptname).textbox('setValue',selectedDept.name)
						}catch(e){
							$('#'+_defaultConfig.usernames).val(names)
							$('#'+_defaultConfig.deptname).val(selectedDept.name)
						}
						
					}else{
						 $('#'+_defaultConfig.userids).val(ids)
						 $('#'+_defaultConfig.deptid).val(selectedDeptId)
						 try{
							$('#'+_defaultConfig.usernames).textbox('setValue',names)
						 	$('#'+_defaultConfig.deptname).textbox('setValue',deptName)
						}catch(e){
							$('#'+_defaultConfig.usernames).val(names)
							$('#'+_defaultConfig.deptname).val(deptName)
						}
						 
					}
				}
				openParam = null;
			}
		},
		// 编辑,flag 为form按钮可见性标志
		reset : function() {
			$typegrid.treegrid('load')
			$detailgrid.datagrid('load')
								
		},
		//执行查询
		doSearch:function(e){
			
			var _param={},queryParams;
			//这里因_moduleConfig.rootId 为main.html页面中的id,
			//为了不影响到后面的功能,此处单独为人员列表弹窗的rootId写死
			var div_dept_user_rootId='div-dept-user'; 
			//获取当前模块配置
			_moduleConfig =private_method.getCurrentConfig();
			//获取class属性为XX.table.dg-detail
			$dg= $('#'+div_dept_user_rootId +" table.dg-detail");
			
			if($dg.length>0){
				//获取条件
				_param = private_method.getConditionAll(div_dept_user_rootId)
				if(_param && !$.isEmptyObject(_param)){
					$dg.datagrid({
					url:'/'+sysmanMain.getRootPath()+'/user/query/getListDomainByDeptid.action',
					queryParams:_param
					})			
					//$dg.datagrid('load', {condition:_param});
//					$dg.datagrid('load', _queryParam);
				}else{
					$dg.datagrid('load');
				}
			}
		},
		
	   /**
		 * 获取查询参数
		 */
		getConditionAll:function(div_dept_user_rootId){
			var _param={}
			//获取当前模块配置
			_moduleConfig =private_method.getCurrentConfig();			
			
			if(_moduleConfig && _moduleConfig.rootId)
			//$dg= $('#'+_moduleConfig.rootId +" table.dg-detail");	
			$dg= $('#'+div_dept_user_rootId +" table.dg-detail");
			if($dg.length>0){
				var _tmpSearch = private_method.getSearchValue(div_dept_user_rootId)
				//var _tmpCondition = private_method.getConditionValue()
				//_param = $.extend({},_tmpSearch,_tmpCondition)
				_param = $.extend({},_tmpSearch)
			}
			
			return _param
			
		},
		
		/*
		 * 获取模糊查找框内容
		 */
		getSearchValue:function(div_dept_user_rootId){
			var _config = private_method.getCurrentConfig();
			var ret={};
			if(_config && div_dept_user_rootId){
				
				$searchbox = $("#"+div_dept_user_rootId +" input.searchbox")
				if($searchbox.length>0){
					var _searchName, _searchValue
					//获取input输入框的值
					_searchValue = $searchbox.val();
					if(_searchValue){
						_searchValue = $.trim(_searchValue)
						if(_searchValue==='')
							return
					}			
						
					//取查询的类型名称
					var _searchName = $($searchbox).attr("name");
					if(_searchName){
						_searchName =$.trim(_searchName)
						if(_searchName===''){
							return
						}															
					}
					
					ret[_searchName]=_searchValue;
					
					return ret
				}
				
			}
		},
		
		// 删除
		cancel : function() {
			if(openParam && openParam.callback && openParam.evt){
				openParam.callback({evt:openParam.evt});	
			}
			$edit_window.window('close')
		},
		onClose:function(){
			$('#'+window_id).empty()
		},
		
		/*
		 * 获取当前模块配置信息
		 */
		getCurrentConfig:function(){
			var _config =sysmanMain.getCurrentModuConfig();
			if(!_config){
				msgServ.Msgslide('获取模块配置信息出错')			
			}			
			return _config
		}
		
	}
	
	var public_method = {
		/**
		 * @param _options.doc	页面根节点
		 * @param _options.docroot	当前业务页面根节点
		 */
		init:function(_options){
			
			private_method.init(_options)
		},
		/**
		 * 脚本打开用户选择页面
		 * 
		 * @param _options.userids	用户id回写字段
		 * @param _options.usernames	用户姓名回写字段
		 * @param _options.deptid		用户部门id回写字段	
		 * @param _options.deptname		用户部门名称回写字段
		 * @param _options.singleSelect 单选模式
		 * @param _options.selectType	人员过滤模式,'owner' 用户所在部门,'job' 用户角色所在部门，'manageDept' 用户管理部门
		 * @param _options.callback		回调函数
		 */
		openPage:function(_options){
			var _path = sysmanMain.getRootPath();
			if(!_path){
				_path = init.getSite()
			}			
			
			var rootpath = '/'+_path
			
			var _window = $('#'+window_id)
			if(_window.length<=0){
				$('body').append("<div id='" + window_id +"'></div>");
			}
			var _config ={
				title:'部门人员选择',
				width:window_width,
				height:window_height,
				window:$('#'+window_id),
				href:rootpath+deptUserSelectUrl,
				flag:false,
				existCheckElement:'#div-dept-user',
				onClose:private_method.onClose
			}
		
			
					
			var _param = $.extend({},_config,_options)
			openParam = _param
			datagridServ.windowEdit(_param);			
		
		},
		initUser:function(_options){
				//初始化用户
				if(_options){
					
				var _usr =sysmanMain.getCurrentUser();
				if(_options.user_name){
					var _el = $('#'+_options.window_id +' #'+_options.user_name)
					
					if(_el.length>0){
						var _v=_el.textbox('getValue')
						if(!_v)
						_el.textbox('setValue',_usr.name)
					}	
				}	
				if(_options.user_id){
					_el = $('#'+_options.window_id +' #'+_options.user_id)
					if(_el.length>0){
						var _v=_el.val();
						if(!_v)
						_el.val(_usr.id)
					}
				}
				
				//初始化部门	
				if(_options.user_deptname){
					_el = $('#'+_options.window_id +' #'+_options.user_deptname)
					if(_el.length>0){
						var _v=_el.textbox('getValue')
						if(!_v)
						_el.textbox('setValue',_usr.deptName)					
					}
				}
				if(_options.user_deptid){
					_el = $('#'+_options.window_id +' #'+_options.user_deptid)
					if(_el.length>0){
						var _v=_el.val();
						if(!_v)
						 _el.val(_usr.deptid);
					}
				}
			}
		}
	}	
	return public_method;
});